package com.youchuang.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.youchuang.action.cart.CartItem;
import com.youchuang.bean.Product;
import com.youchuang.common.CartFactory;
import com.youchuang.dao.ProductDAO;
import com.youchuang.service.CartService;
import com.youchuang.util.TransforDigitUtil;

@Transactional
@Service("cartService")
@Lazy(true)
public class CartServiceImpl implements CartService {

	@Resource
	private ProductDAO productDAO;

	@Transactional
	@Override
	public void buy(String id) {
		String resultId = id.trim();
		Map<String, CartItem> store = CartFactory.getCart().getStore();

		if (store.containsKey(resultId)) {
			CartItem cartItem = store.get(resultId);
			cartItem.setNum(cartItem.getNum() + 1);
		} else {
			CartItem cartItem = new CartItem();
			Product product = productDAO.queryById(resultId);
			cartItem.setProduct(product);
			store.put(resultId, cartItem);
		}

	}

	@Override
	public void delete(String id) {
		Map<String, CartItem> store = CartFactory.getCart().getStore();
		if (store.containsKey(id)) {
			store.get(id).setDelete(true);
		}
	}

	@Override
	public List<CartItem> getItems(boolean delete) {
		Map<String, CartItem> store = CartFactory.getCart().getStore();
		List<CartItem> cartItems = new ArrayList<>();
		for (CartItem cartItem : store.values()) {
			if (cartItem.isDelete() == delete) {
				cartItems.add(cartItem);
			}
		}
		return cartItems;
	}

	@Override
	public void recovery(String id) {
		Map<String, CartItem> store = CartFactory.getCart().getStore();
		if (store.containsKey(id)) {
			store.get(id).setDelete(false);
		}
	}

	@PreDestroy
	@Override
	public void clearCart() {
		Map<String, CartItem> store = CartFactory.getCart().getStore();
		store.clear();
	}

	@Override
	public double total(boolean flag) {
		double totalPrice = 0.0;
		if (flag) {
			for (CartItem cartItem : getItems(false)) {
				totalPrice += cartItem.getNum() * cartItem.getProduct().getFixedPrice();
			}
		} else {
			for (CartItem cartItem : getItems(false)) {
				totalPrice += cartItem.getNum() * cartItem.getProduct().getDangPrice();
			}
		}
		totalPrice = TransforDigitUtil.transformNumber(totalPrice);
		return totalPrice;
	}

	@Override
	public void update(String id, int num) {
		Map<String, CartItem> store = CartFactory.getCart().getStore();
		if (store.containsKey(id)) {
			store.get(id).setNum(num);
		}
	}
}
